const express = require("express");
const { db } = require("../database");
const { CustomerAuth } = require("../middles");
const { avatar } = require("../upload");
const { sign } = require("../jwt");
const { makePassword, checkPassword } = require("../utils");

const { validate, validators } = require("../validate");

// 无需身份验证的路由
const notAuthRouter = express.Router();
notAuthRouter
  .post(
    "/login",
    validate([validators.email, validators.password]),
    async (req, res) => {
      const { email, password } = req.body;
      // 根据用户名查询用户信息
      const customer = await db.findOne(
        "select * from customer where email = ?",
        [email]
      );
      // 判断密码是否输入正确
      if (customer && checkPassword(password, customer.password)) {
        // 在会话（session）中保存用户信息
        req.session.userId = customer.id;
        // 签发 token 给客户端代码
        const token = sign({ userId: customer.id });
        return res.send({
          success: true,
          object: customer,
          token,
        });
      }
      res.send({ success: false, message: "用户名或密码错误！" });
    }
  )
  .post(
    "/register",
    avatar.single("avatar"),
    validate([
      validators.email,
      validators.password,
      validators.confirmPassword,
      validators.nickname,
      validators.mobile,
    ]),
    async (req, res) => {
      const { email, password, nickname, mobile, birthday, gender } = req.body;
      const exist = await db.findOne("select * from customer where email = ?", [
        email,
      ]);
      if (exist)
        return res.send({
          success: false,
          errors: { email: ["该邮件地址已经注册过！"] },
        });
      const results = await db.select(
        "insert into customer (email, nickname, password, mobile, birthday, gender, avatar) values (?,?,?,?,?,?,?)",
        [
          email,
          nickname,
          makePassword(password),
          mobile,
          birthday,
          gender,
          req.file?.filename ? "/avatars/" + req.file?.filename : null,
        ]
      );
      const customer = await db.findOne("select * from customer where id = ?", [
        results.insertId,
      ]);
      res.send({
        success: true,
        object: customer,
      });
    }
  );

const router = express.Router();
// CustomerAuth 中间件实现对登录用户的验证，如果验证通过，就会有 req.user 属性。
router.use(CustomerAuth);
// 定义路由
router.get("/profile", async (req, res) => {
  res.send({
    success: true,
    object: req.user,
  });
});

const registerRouter = (app) => {
  app.use("/customer", notAuthRouter);
  app.use("/customer", router);
};

module.exports = { registerRouter };
